<!--
* description: 财务管理-网点备件资金账户配置
* author: wangjuan
* createdDate: 2021-3-2
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :callback-obj="callbackObj"
    />

  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/pa/financialManagement'

export default {
  name: 'OutletSparePartsfundAccountAllocation',

  components: {
    OneTableTemplate
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      selectData: [],
      rowData: {},
      // 网格查询API配置对象
      apiConfig: api.queryDlrPartCapitalAccountSetInfo,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'),
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'confirm',
          clickEvent: () => this.save(),
          text: '保存'
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset')
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          name: 'importTemplate',
          icon: 'iconfont icon-importTemplate',
          clickEvent: () => this.handFileListChange(),
          text: '导入',
          position: 'upload'
        },
        {
          compKey: 'btnKey5',
          type: 'text',
          size: 'small',
          name: 'importTemplateDownload',
          icon: 'iconfont  icon-importTemplateDownload',
          click: () => this.templateDownload(),
          text: 'Excel导入模板下载',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '网点类型：',
              codeField: 'dlrType',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'dlrType,dlrTypeCn',
              options: [
                { dlrType: '1', dlrTypeCn: '直营店' },
                { dlrType: '2', dlrTypeCn: '授权店' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '网点编码：',
              codeField: 'dlrCode',
              component: () => import('@/components/pa/dlrCode'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '网点名称：',
              codeField: 'dlrShortName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              disabled: true,
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '账户类型：',
              codeField: 'isCashSettle',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'isCashSettle,isCashSettleCn',
              options: [
                { isCashSettle: '0', isCashSettleCn: '信用额度' },
                { isCashSettle: '1', isCashSettleCn: '现金账户' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '状态：',
              codeField: 'isEnable',
              textField: 'isEnableCn',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'isEnable,isEnableCn',
              customObj: {
                api: api.isEnable,
                selectType: '1',
                listQuery: {
                  isEnable: ''
                }
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'dlrAccountId',
              label: '账户ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'dlrCode',
              label: '网点编码'
            },
            {
              prop: 'dlrShortName',
              label: '网点名称'
            },
            {
              prop: 'dlrTypeCn',
              label: '网点类型'
            },
            {
              prop: 'isCashSettle',
              label: '现金账户',
              isComponent: true,
              isColComp: true,
              comps: [
                {
                  compKey: 'audit',
                  codeField: 'isCashSettle',
                  disabled: false,
                  component: () => import('@/components/org/checkBox')
                }
              ]
            },
            {
              prop: 'isCreditSettle',
              label: '信用额度账户',
              isComponent: true,
              isColComp: true,
              comps: [
                {
                  compKey: 'audit',
                  codeField: 'isCreditSettle',
                  disabled: false,
                  component: () => import('@/components/org/checkBox')
                }
              ]
            },
            {
              prop: 'isEnable',
              label: '状态',
              isComponent: true,
              isColComp: true,
              comps: [
                {
                  isAsync: false,
                  clearable: false,
                  compKey: 'compKey5' + this.$utils.generateId(),
                  codeField: 'isEnable',
                  textField: 'isEnableCn',
                  component: () => import('@/components/org/commonSelect'),
                  oFields: 'isEnable,isEnableCn',
                  customObj: {
                    api: api.isEnable,
                    selectType: '1',
                  },
                  type: 'dropdownList',
                  isMul: false
                }
              ]
            },
            {
              prop: 'remark',
              label: '备注',
              isComponent: true,
              comps: [
                {
                  compKey: 'compKey5' + this.$utils.generateId(),
                  codeField: 'remark',
                  component: () => import('@/components/org/commonInput'),
                  type: 'inputText'
                }
              ]
            }
          ],
      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        dlrType: '',
        dlrCode: '',
        dlrShortName: '',
        isEnable: '',
        isEnableCn:'',
        isCashSettle: '',
        dlrAccountId: '',
        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectData = selection

          this.handleSelectionChange(selection)
        }
      }
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    save() {
      if (!this.selectData.length) return this.$message('请至少勾选一条数据进行保存操作！')
      const that = this
      const datas = []
      this.selectData.forEach(function(val, index) {
        datas.push({
          dlrType: val.dlrType,
          dlrCode: val.dlrCode,
          dlrShortName: val.dlrShortName,
          isEnable: val.isEnable,
          isCashSettle: val.isCashSettle,
          isCreditSettle: val.isCreditSettle,
          remark: val.remark || '',
          dlrAccountId: val.dlrAccountId,
          updateControlId: val.updateControlId
        })
      })
      const queryObj = {
        apiConfig: api.saveCapitalAccount,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: datas
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === '0') {
          return
        }
        var getResult = response
        if (getResult.result === '1') {
          that.$message({
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          that.queryTable(1)
        } else {
          that.$message({
            message: getResult.msg,
            type: 'warning',
            duration: 2000
          })
        }
      })
    },

    // 导入
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType !== 'xls' && fileType !== 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const that = this
      const url = api.accountImportExcel.APIUrl
      that
        .$requestUpload(url, param)
        .then(response => {
          loading.close()
          if (response.result === '1') {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            that.queryTable()
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch(_ => {})
    },

    // 模板下载
    templateDownload() {
      this.$requestAPI({
        variables: { dataType: 'excel' },
        apiUrl: api.accountDownloadTemplate.APIUrl
      }).then(res => {
        this.$utils.downloadFile(res, '网点备件资金账户配置导入模板下载.xlsx')
      })
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/.el-tooltip .el-checkbox{
  padding-top: 16px ;
}
</style>
